#include "SortedLinkedList.h"

SortedLinkedList::SortedLinkedList()
{
   mpHead = NULL;
}

SortedLinkedList::~SortedLinkedList()
{
   removeAllWords();
}

/*
Pre: None
Post: A node has been created in the linked list that contains the word, and is in order alphebetically.
Purpose: To insert a node with an arbitrary word into the linked list in alphabetical order. 
*/
void SortedLinkedList::addWord( const string& theWord )
{
	//create a ListNode
	ListNode* pNode = new ListNode( theWord );

	if( mpHead != NULL )//head exists
	{
		//Checks if the word getting added is alphabetically before the word contained in the head node
		if ( toLowerCase( theWord ) < toLowerCase( mpHead->word ) )
		{
			pNode->pNextNode = mpHead;
			mpHead = pNode;
		}
		else
		{
			ListNode* pCurrent = mpHead;
			
			//Iterates through the list until either the end of the list is reached or the new word is greater than the current word
			while( pCurrent->pNextNode != NULL && toLowerCase( theWord ) > toLowerCase( pCurrent->pNextNode->word ) )
			{
				pCurrent = pCurrent->pNextNode;
			}

			//Insert the word into the list after the current node
			pNode->pNextNode = pCurrent->pNextNode;
			pCurrent->pNextNode = pNode;
		}
	}
	else//head doesn't exist
	{
		mpHead = pNode;
	}
}


/*
Pre: None
Post: A copy of the input string has been converted to lower case.
Purpose: To return a lower case copy of an input string.
*/
string toLowerCase( const string &str ) 
{
	string tempStr = str;

	for ( int i=0; i < str.length(); ++i )
	{
		tempStr[i] = tolower( str[i] );
	}

	return tempStr;
}